<?php


namespace app\controllers;


use app\components\BaseAuthController;
use app\helpers\BinHelper;
use app\models\Group;
use app\models\GroupUser;
use app\models\User;
use Throwable;
use Yii;
use yii\db\Exception;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class UserController extends BaseAuthController {

    public $name = '用户';

    public function actionIndex() {
        $model = new User();
        $imsi = $this->getParam('imsi');
        if (!empty($imsi)) {
            $model->where = ['like', 'imsi', $imsi];
        }
        $phone = $this->getParam('phone');
        if (!empty($phone)) {
            if ($model->where) {
                $model->where = ['and', $model->where, ['like', 'phone', $phone]];
            } else {
                $model->where = ['like', 'phone', $phone];
            }
        }
        $dataProvider = $model->search([]);
        return $this->render(compact('dataProvider', 'model'));
    }


    public function actionView($id = NULL) {
        $model = User::findOne($id);
        if (!$model) {
//            Yii::$app->session->setFlash('error', '用户不存在');
//            return $this->redirect(["{$this->id}/index"]);
            throw new NotFoundHttpException('用户不存在');
        }
        $output = BinHelper::run('UserGet', $model->imsi);
        if (is_array($output) && isset($output[1])) {
            User::parseString($output[1]);
        }

        return $this->render(compact('model'));
    }


    /**
     * @param null $id
     * @return array|bool|string
     * @throws Exception
     * @throws NotFoundHttpException
     */
    public function actionSave($id = NULL) {
        /* @var $model User */
        $model = $this->findModel($id, User::class);
        if (!$model->load($this->post())) {
            return $this->render(compact('model'));
        }
        $res = $model->save();
        if (!$model->isNewRecord) {
            $output = BinHelper::run('UserUpt', $model->imsi);
            $this->message($output);
        }
        return $res;
    }

    /**
     * @throws Exception
     */
    public function actionYb() {
        return $this->handler('yb');
    }

    /**
     * @throws Exception
     */
    public function actionGps() {
        return $this->handler('gps');
    }

    /**
     * @throws Exception
     */
    public function actionYy() {
        return $this->handler('yy');
    }

    /**
     * @param $field
     * @return Response
     * @throws Exception
     */
    protected function handler($field) {
        $id = trim($this->get('id'), ',');
        $v = intval($this->get('v'));
        $idList = explode(',', $id);
        $models = User::findAll(['id' => $idList]);
        foreach ($models as $model) {
            $model->setAttribute($field, $v);
            $model->save(FALSE);

            $map = ['gps_1' => 'GpsOn', 'gps_0' => 'GpsOff', 'yy_1' => 'UserStun', 'yy_0' => 'UserRestore', 'yb_1' => 'UserKill', 'yb_0' => 'UserRevive'];
            $a = $map["{$field}_{$v}"];
            BinHelper::run($a, $model->imsi);
        }
        Yii::$app->session->setFlash('info', '操作完成');
        return $this->redirect(["{$this->id}/index"]);
    }


    public function actionDelete() {
        $id = intval($this->get('id'));
        $model = User::findOne($id);
        if (!$model) {
            Yii::$app->session->setFlash('error', '用户不存在');
            return $this->redirect(["{$this->id}/index"]);
        }

        $phone = $model->phone;
        $imsi = $model->imsi;
        $file = FILE_ROOT . "/{$imsi}.info";
        $phoneFile = FILE_ROOT . "/{$phone}.info";

        try {
            if (!@unlink($file)) {
                throw new Exception("删除UE文件: {$file}失败");
            }

            @unlink($phoneFile);

            $model->delete();
            $groupUsers = GroupUser::find()->where(['phone' => $phone])->asArray()->groupBy('group_num')->all();
            foreach ($groupUsers as $groupUser) {
                /* @var $group Group */
                $group = Group::find()->where(['group_num' => $groupUser['group_num']])->one();
                if ($group) {
                    Group::generateFiles($group);
                }
            }
            GroupUser::deleteAll(['phone' => $phone]);

            $output = BinHelper::run('UserDel', $imsi);
            $this->message($output);

        } catch (Exception $e) {
            Yii::$app->session->setFlash('error', $e->getMessage());
        } catch (Throwable $e) {
            Yii::$app->session->setFlash('error', $e->getMessage());
        }
        return $this->redirect(["{$this->id}/index"]);
    }
}